<template>
  <div class="chat-panel">
    <div class="chat-header">
      <div class="chat-header-left">
        <h4 class="mb-0">对话记录</h4>
        <span v-if="messages.length > 0" class="message-count">({{ messages.length }})</span>
      </div>
      <div class="chat-header-right">
        <button 
          class="btn btn-sm btn-outline-secondary"
          @click="exportMessages"
          :disabled="messages.length === 0"
          title="导出消息"
        >
          <i class="bi bi-download"></i>
        </button>
        <button 
          class="btn btn-sm btn-outline-secondary ms-2"
          @click="clearMessages"
          :disabled="messages.length === 0"
          title="清空消息"
        >
          <i class="bi bi-trash"></i>
        </button>
      </div>
    </div>
    
    <div class="chat-messages" ref="chatContainer">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-icon">
          <i class="bi bi-comments-dots"></i>
        </div>
        <h3>欢迎使用LiveTalking</h3>
        <p>数字人语音交互平台</p>
        <p class="welcome-subtitle">点击下方麦克风按钮开始与数字人对话</p>
      </div>
      
      <!-- 聊天消息列表 -->
      <div 
        v-for="message in messages" 
        :key="message.id"
        class="message-item"
        :class="message.type"
        :data-status="message.status"
      >
        <!-- 消息头像 -->
        <div class="message-avatar">
          <i :class="getMessageAvatar(message.type)"></i>
          <span v-if="message.status === 'sending'" class="message-status-indicator sending"></span>
          <span v-else-if="message.status === 'error'" class="message-status-indicator error"></span>
        </div>
        
        <!-- 消息内容 -->
        <div class="message-content">
          <div class="message-header">
            <span class="message-author">{{ getMessageAuthor(message.type) }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            <button 
              v-if="message.type === 'system'" 
              class="btn-copy-message btn-sm"
              @click="copyMessage(message.text)"
              title="复制消息"
            >
              <i class="bi bi-clipboard"></i>
            </button>
          </div>
          <div class="message-text" :class="{ 'is-voice': message.isVoice }">
            <template v-if="message.isVoice">
              <div class="voice-message-wrapper" @click="playVoiceMessage(message)">
                <i class="bi bi-play-circle"></i>
                <div class="voice-wave">
                  <span></span>
                  <span></span>
                  <span></span>
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <span class="voice-duration">{{ getVoiceDuration(message.duration) }}</span>
              </div>
            </template>
            <template v-else>
              {{ message.text }}
            </template>
          </div>
          
          <!-- 消息状态标签 -->
          <div v-if="message.type === 'user' && message.status" class="message-status">
            <span v-if="message.status === 'sending'" class="status-sending">发送中...</span>
            <span v-else-if="message.status === 'sent'" class="status-sent">已发送</span>
            <span v-else-if="message.status === 'delivered'" class="status-delivered">已送达</span>
            <span v-else-if="message.status === 'read'" class="status-read">已读</span>
            <span v-else-if="message.status === 'error'" class="status-error">发送失败</span>
          </div>
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="loading-indicator">
        <div class="loading-spinner"></div>
        <span>数字人正在思考...</span>
      </div>
    </div>
    
    <!-- 底部工具栏 -->
    <div v-if="messages.length > 0" class="chat-footer">
      <div class="chat-stats">
        <span>总消息数: {{ messages.length }}</span>
        <span>最后更新: {{ formatLastUpdateTime() }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, computed } from 'vue'

// Props
const props = defineProps({
  initialMessages: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['message-added', 'messages-cleared', 'copy-message', 'play-voice-message'])

// 响应式数据
const messages = ref([...props.initialMessages])
const isLoading = ref(props.loading)
const chatContainer = ref(null)
const playingVoiceId = ref(null)
const lastUpdateTime = ref(null)

// 计算属性
const scrollPosition = computed(() => {
  if (!chatContainer.value) return 0
  return chatContainer.value.scrollTop
})

// 监听props变化
watch(() => props.loading, (newVal) => {
  isLoading.value = newVal
})

watch(() => props.initialMessages, (newVal) => {
  if (newVal && newVal.length !== messages.value.length) {
    messages.value = [...newVal]
  }
}, { deep: true })

// 监听消息变化，自动滚动到底部
watch(messages, async (newMessages) => {
  if (newMessages && newMessages.length > 0) {
    lastUpdateTime.value = Date.now()
  }
  
  await nextTick()
  scrollToBottom()
}, { deep: true, immediate: true })

// 监听滚动位置，实现消息自动加载更多功能的基础
watch(scrollPosition, (newPosition) => {
  // 可以在这里实现滚动到顶部加载更多消息的逻辑
})

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}

// 格式化最后更新时间
function formatLastUpdateTime() {
  if (messages.value.length === 0) return ''
  const lastMessage = messages.value[messages.value.length - 1]
  return new Date(lastMessage.timestamp).toLocaleString()
}

// 获取消息头像
function getMessageAvatar(type) {
  switch (type) {
    case 'user':
      return 'bi bi-person-circle'
    case 'system':
      return 'bi bi-robot'
    case 'info':
      return 'bi bi-info-circle'
    case 'error':
      return 'bi bi-exclamation-circle'
    default:
      return 'bi bi-message-square'
  }
}

// 获取消息作者
function getMessageAuthor(type) {
  switch (type) {
    case 'user':
      return '您'
    case 'system':
      return '数字人'
    case 'info':
      return '系统提示'
    case 'error':
      return '错误信息'
    default:
      return '未知'
  }
}

// 获取语音消息时长
function getVoiceDuration(duration) {
  if (!duration) return ''
  const minutes = Math.floor(duration / 60)
  const seconds = Math.floor(duration % 60)
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
}

// 滚动到底部
function scrollToBottom() {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 滚动到特定消息
function scrollToMessage(messageId) {
  nextTick(() => {
    const messageElement = document.querySelector(`[data-message-id="${messageId}"]`)
    if (messageElement && chatContainer.value) {
      chatContainer.value.scrollTop = messageElement.offsetTop - 100
    }
  })
}

// 添加消息
function addMessage(text, type = 'system', options = {}) {
  const message = {
    id: Date.now(),
    text: text,
    type: type,
    timestamp: Date.now(),
    ...options
  }
  
  messages.value.push(message)
  emit('message-added', message)
  
  return message
}

// 添加用户消息
function addUserMessage(text, options = {}) {
  return addMessage(text, 'user', options)
}

// 添加系统消息
function addSystemMessage(text, options = {}) {
  return addMessage(text, 'system', options)
}

// 清空消息
function clearMessages() {
  if (messages.value.length > 0) {
    if (confirm('确定要清空所有对话记录吗？')) {
      messages.value = []
      emit('messages-cleared')
      playingVoiceId.value = null
    }
  }
}

// 导出消息
function exportMessages() {
  if (messages.value.length === 0) return
  
  try {
    // 构建导出内容
    let exportContent = 'LiveTalking 对话记录\n' +
                      '导出时间: ' + new Date().toLocaleString() + '\n' +
                      '总消息数: ' + messages.value.length + '\n\n'
    
    // 添加每条消息
    messages.value.forEach((message) => {
      const author = getMessageAuthor(message.type)
      const time = new Date(message.timestamp).toLocaleString()
      const content = message.text || (message.isVoice ? `[语音消息 ${getVoiceDuration(message.duration)}]` : '[无内容]')
      
      exportContent += `${author} ${time}\n${content}\n\n`
    })
    
    // 创建下载链接
    const blob = new Blob([exportContent], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `LiveTalking对话记录_${new Date().toISOString().slice(0, 10)}.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    // 提示用户导出成功
    emit('copy-message', '对话记录导出成功')
  } catch (error) {
    console.error('导出消息失败:', error)
    emit('copy-message', '导出失败，请重试')
  }
}

// 复制消息
function copyMessage(text) {
  if (!text) return
  
  navigator.clipboard.writeText(text).then(() => {
    emit('copy-message', '消息已复制到剪贴板')
  }).catch(err => {
    console.error('复制失败:', err)
    emit('copy-message', '复制失败，请手动复制')
  })
}

// 播放语音消息
function playVoiceMessage(message) {
  if (!message.isVoice || !message.voiceUrl) return
  
  emit('play-voice-message', message)
  
  // 更新播放状态
  playingVoiceId.value = playingVoiceId.value === message.id ? null : message.id
  
  // 模拟语音播放结束
  setTimeout(() => {
    if (playingVoiceId.value === message.id) {
      playingVoiceId.value = null
    }
  }, message.duration * 1000)
}

// 重新加载消息列表（用于错误恢复）
function reloadMessages() {
  // 清空滚动到顶部
  if (chatContainer.value) {
    chatContainer.value.scrollTop = 0
  }
  
  // 延迟后滚动到底部
  setTimeout(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  }, 100)
}

// 窗口大小变化处理
function handleResize() {
  // 可以在这里添加布局调整逻辑
}

// 组件挂载
nextTick(() => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
})

// 监听窗口大小变化
window.addEventListener('resize', handleResize)

// 组件卸载前清理
const cleanup = () => {
  window.removeEventListener('resize', handleResize)
  playingVoiceId.value = null
}

// 暴露方法给父组件
defineExpose({
  addMessage,
  addUserMessage,
  addSystemMessage,
  clearMessages,
  exportMessages,
  copyMessage,
  playVoiceMessage,
  scrollToMessage,
  reloadMessages,
  messages,
  playingVoiceId,
  cleanup
})
</script>

<style scoped>
.chat-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  position: relative;
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafbfc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  backdrop-filter: blur(10px);
  position: sticky;
  top: 0;
  z-index: 10;
}

.chat-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-header h4 {
  margin: 0;
  font-size: 17px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.3px;
}

.message-count {
  background-color: #e74c3c;
  color: white;
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.chat-header-right {
  display: flex;
  gap: 8px;
}

.chat-header-right .btn {
  transition: all 0.3s ease;
  border-radius: 20px;
  padding: 6px 12px;
  min-width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  color: #666;
  font-size: 14px;
}

.chat-header-right .btn:hover:not(:disabled) {
  background-color: #f5f5f5;
  border-color: #d0d0d0;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.chat-header-right .btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
  min-height: 300px;
  max-height: 500px; /* 限制最大高度，防止无限延伸 */
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  transition: background 0.3s;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  color: #666;
  padding: 40px;
}

.welcome-icon {
  font-size: 64px;
  color: #e0e0e0;
  margin-bottom: 20px;
  animation: pulse 2s infinite;
}

.welcome-message h3 {
  margin: 0 0 8px 0;
  font-size: 22px;
  font-weight: 600;
  color: #2c3e50;
}

.welcome-message p {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #666;
}

.welcome-subtitle {
  font-size: 14px;
  color: #999;
  line-height: 1.4;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.4s ease-out;
  position: relative;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-item.user .message-content {
  background: linear-gradient(135deg, #4f46e5 0%, #4338ca 100%);
  color: white;
  margin-right: 0;
  margin-left: 20px;
  border-radius: 20px 20px 4px 20px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.message-item.system .message-content {
  background-color: #ffffff;
  color: #333;
  margin-left: 20px;
  border-radius: 20px 20px 20px 4px;
  border: 1px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-item.info .message-content {
  background-color: #fff3e0;
  color: #e65100;
  margin-left: 20px;
  border-radius: 20px;
  border: 1px solid #ffe0b2;
}

.message-item.error .message-content {
  background-color: #ffebee;
  color: #c62828;
  margin-left: 20px;
  border-radius: 20px;
  border: 1px solid #ffcdd2;
}

/* 消息状态指示 */
.message-item[data-status="sending"] {
  opacity: 0.8;
}

.message-item[data-status="error"] {
  animation: shake 0.5s;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
  20%, 40%, 60%, 80% { transform: translateX(2px); }
}

.message-avatar {
  width: 44px;
  height: 44px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 22px;
  color: white;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-item.system .message-avatar {
  background: linear-gradient(135deg, #4ecdc4 0%, #45b7aa 100%);
}

.message-item.info .message-avatar {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
}

.message-item.error .message-avatar {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.message-status-indicator {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 2px solid white;
}

.message-status-indicator.sending {
  background-color: #ff9800;
  animation: pulse 1.5s infinite;
}

.message-status-indicator.error {
  background-color: #f44336;
}

.message-content {
  max-width: 75%;
  padding: 14px 18px;
  border-radius: 20px;
  word-wrap: break-word;
  background-color: #f5f5f5;
  margin-right: 20px;
  position: relative;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
  gap: 8px;
}

.message-author {
  font-weight: 600;
  opacity: 0.9;
}

.message-item.user .message-author {
  color: rgba(255, 255, 255, 0.9);
}

.message-time {
  color: #999;
  font-size: 11px;
  opacity: 0.8;
}

.message-item.user .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.btn-copy-message {
  background: transparent;
  border: none;
  color: inherit;
  font-size: 12px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  opacity: 0.7;
  transition: all 0.2s;
}

.btn-copy-message:hover {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.05);
}

.message-item.user .btn-copy-message:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.message-text {
  font-size: 15px;
  line-height: 1.5;
  word-break: break-word;
  white-space: pre-wrap;
}

/* 语音消息样式 */
.message-text.is-voice {
  display: flex;
  align-items: center;
}

.voice-message-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 8px 12px;
  border-radius: 12px;
  background-color: rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s;
}

.message-item.user .voice-message-wrapper {
  background-color: rgba(255, 255, 255, 0.1);
}

.voice-message-wrapper:hover {
  transform: translateX(2px);
  background-color: rgba(0, 0, 0, 0.08);
}

.message-item.user .voice-message-wrapper:hover {
  background-color: rgba(255, 255, 255, 0.15);
}

.voice-wave {
  display: flex;
  align-items: center;
  gap: 3px;
  flex: 1;
}

.voice-wave span {
  width: 4px;
  height: 12px;
  background-color: #666;
  border-radius: 2px;
  animation: voiceWave 1.2s infinite ease-in-out;
}

.message-item.user .voice-wave span {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 语音波形动画 */
.voice-wave span:nth-child(1) { animation-delay: 0s; }
.voice-wave span:nth-child(2) { animation-delay: 0.1s; }
.voice-wave span:nth-child(3) { animation-delay: 0.2s; }
.voice-wave span:nth-child(4) { animation-delay: 0.3s; }
.voice-wave span:nth-child(5) { animation-delay: 0.4s; }
.voice-wave span:nth-child(6) { animation-delay: 0.5s; }

@keyframes voiceWave {
  0%, 100% { height: 8px; }
  50% { height: 24px; }
}

.voice-duration {
  font-size: 13px;
  color: #666;
  font-weight: 500;
  min-width: 30px;
  text-align: right;
}

.message-item.user .voice-duration {
  color: rgba(255, 255, 255, 0.8);
}

/* 消息状态标签 */
.message-status {
  font-size: 11px;
  margin-top: 4px;
  text-align: right;
}

.status-sending {
  color: #ff9800;
  animation: blink 1.5s infinite;
}

.status-sent {
  color: #666;
}

.status-delivered {
  color: #4caf50;
}

.status-read {
  color: #2196f3;
}

.status-error {
  color: #f44336;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
  animation: fadeIn 0.3s ease-in;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4f46e5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

/* 底部工具栏 */
.chat-footer {
  padding: 12px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafbfc;
  position: sticky;
  bottom: 0;
}

.chat-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

/* 动画定义 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(15px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.05); opacity: 0.8; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-panel {
    height: 100vh;
    border-radius: 0;
    box-shadow: none;
  }
  
  .chat-header, .chat-footer {
    padding: 12px 16px;
  }
  
  .chat-messages {
    padding: 16px;
  }
  
  .message-content {
    max-width: 85%;
    padding: 12px 16px;
  }
  
  .message-avatar {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }
  
  .welcome-icon {
    font-size: 48px;
  }
  
  .welcome-message h3 {
    font-size: 18px;
  }
  
  .chat-stats {
    flex-direction: column;
    gap: 4px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .message-content {
    max-width: 90%;
  }
  
  .chat-header-right .btn {
    min-width: 32px;
    height: 32px;
    padding: 4px 8px;
  }
}

/* 打印样式 */
@media print {
  .chat-header, .chat-footer {
    display: none;
  }
  
  .chat-messages {
    height: auto;
    overflow: visible;
  }
  
  .message-item {
    break-inside: avoid;
    page-break-inside: avoid;
  }
}
</style>